﻿using System.Collections;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using Kratos.Framework.Configurations;
using Kratos.Framework.Extensions.RouteExtensions;
using Kratos.Framework.Infrastructures;
using Microsoft.Practices.Unity;

namespace Kratos.Framework.BootStrapTasks
{
    public class LoadModules : IBootStrapTasks
    {
        private readonly IUnityContainer _container;

        //Ioc构造注入
        public LoadModules(IUnityContainer container)
        {
            _container = container;
        }

        #region IBootStrapTasks Memembers
        public void Execute()
        {
            var kratosSection = _container.Resolve<KratosConfigurationSection>();
            var routes = _container.Resolve<RouteCollection>();
            var moduleLoaded = _container.Resolve<IModulesLoaded>();
            var modelBinders = _container.Resolve<ModelBinderDictionary>();

            //获取返回与dataPrivider相等的模块的实例
            foreach (var moduleInstance in kratosSection.Modules.Cast<KratosModuleConfigurationElement>().Select(module => moduleLoaded.Load(kratosSection, module)).Where(moduleInstance => moduleInstance != null))
            {
                moduleInstance.Initialize();
                moduleInstance.RegisterModelBinders(modelBinders);
                moduleInstance.RegisterBizServices();
                moduleInstance.RegisterAction();
            }

            //注册所有模块的路由
            routes.LoadFromModules(moduleLoaded);
        }

        public void CleanUp()
        {
            _container.Resolve<IModulesLoaded>().UnloadModules();
        }
        #endregion
    }
}
